#include "datamodelbuilder.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QStringList>
#include <QDir>
#include <QDebug>

DataModelBuilder::DataModelBuilder()
{
}

DataModel *DataModelBuilder::getModel(QObject *parent)
{
    QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");

    QString path(QDir::home().path());
    path.append(QDir::separator()).append("download_manager.sqlite");
    path = QDir::toNativeSeparators(path);
    database.setDatabaseName(path);

    if (!database.isValid())
    {
        qDebug() << "Error: Invalid database driver";
    }
    if (!database.open())
    {
        qDebug() << "Error: Can't open database";
        return 0;
    }

    if (!database.tables().contains("download"))
    {
        QSqlQuery query;
        QString str = "CREATE TABLE download ("
                      "id integer PRIMARY KEY NOT NULL, "
                      "url VARCHAR(2048), "
                      "local VARCHAR(2048),"
                      "progress integer"
                      ");";
        if (!query.exec(str)) {
            qDebug() << "Can't exec CREATE TABLE query";
        }
//        QSqlQuery insert_query;

        QString str_insert = "INSERT INTO download(url, local, progress) "
                    "VALUES (:url, :local, :progress);";
        query.prepare(str_insert);
        query.bindValue(":url", "http://localhost");
        query.bindValue(":local", "/tmp/foo");
        query.bindValue(":progress", 48);

        if (!query.exec()) {
            qDebug() << "Can't exec INSERT query";
        }
    }

    return new DataModel(parent, database);
}
